
import React, { useState, useEffect } from 'react';
import styles from './scroll.less';

function getScrollTop() {
  return document.documentElement.scrollTop || document.body.scrollTop;
}

function getScrollHeight() {
  return document.documentElement.scrollHeight || document.body.scrollHeight;
}

function getOffsetHeight() {
  return document.documentElement.offsetHeight || document.body.offsetHeight;
}

function useTraceScroll() {
  const [scrollTop, setScrollTop] = useState(0);
  useEffect(() => {
    window.onscroll = function() {
      //为了保证兼容性，这里取两个值，哪个有值取哪一个
      //scrollTop就是触发滚轮事件时滚轮的高度
      console.log(getScrollTop());
      setScrollTop(getScrollTop());
    }
  }, []);
  return [scrollTop, getScrollHeight() - getOffsetHeight() - scrollTop];
}

const NearThres = 60;

export default function ScrollDetect() {
   const [scrollTop, scrollBottom] = useTraceScroll();
   const classes = [styles.wrapper];
   if (scrollTop < NearThres) {
     classes.push(styles.nearTop);
   } else if (scrollBottom < NearThres) {
     classes.push(styles.nearBottom);
   } else {
     classes.push(styles.inMiddle);
   }
   return (
     <div className={classes.join(' ')}>
       <div>距离顶部{scrollTop} 距离底部{scrollBottom}</div>
     </div>
   )
}
